import sys
import tornado.ioloop
import tornado.web
from playhouse.migrate import SqliteMigrator, migrate, TextField, OperationalError

import settings
from db.user import User

from route.All import urls

__author__ = 'cyh'

application = tornado.web.Application(urls, **settings.settings)


def initDB():
    from db.model import Article, Static
    # try:

    User.db.connect()
    if not Article.table_exists():
        User.db.create_table(Article)
    if not Static.table_exists():
        User.db.create_table(Static)
    try:
        migrator = SqliteMigrator(User.db)
        html_field = TextField(default='')
        migrate(
            migrator.add_column('article', 'html', html_field),)
    except OperationalError:
        print 'exist'


ex = ['.', '/', '\\']

if __name__ == "__main__":
    port = int(sys.argv[1])
    name = str(sys.argv[2])
    password = str(sys.argv[3])

    for s in ex:
        name = name.replace(s, 'a')

    User.user_info['name'] = name
    User.user_info['port'] = port
    User.user_info['password'] = password

    path = './data/%s.db' % name
    print path

    User.db.init(path)
    initDB()
    print "start ok"
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
